import 'dart:async';
import 'dart:io';
import 'package:lishopflu/base/base_import.dart';
import 'package:lishopflu/base/view_import.dart';
import 'package:lishopflu/global/const_key.dart';
import 'package:lishopflu/router/app_navigator.dart';
import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_location/amap_location_option.dart';
import 'package:permission_handler/permission_handler.dart';

typedef LocationCall = Future Function(Map<String, Object>);

class LocationUtil{

  /*
    获取当前定位结果

    /// `callbackTime`:回调时间，格式为"yyyy-MM-dd HH:mm:ss"
  ///
  /// `locationTime`:定位时间， 格式为"yyyy-MM-dd HH:mm:ss"
  ///
  /// `locationType`:  定位类型， 具体类型可以参考https://lbs.amap.com/api/android-location-sdk/guide/utilities/location-type
  ///
  /// `latitude`:纬度
  ///
  /// `longitude`:精度
  ///
  /// `accuracy`:精确度
  ///
  /// `altitude`:海拔, android上只有locationType==1时才会有值
  ///
  /// `bearing`: 角度，android上只有locationType==1时才会有值
  ///
  /// `speed`:速度， android上只有locationType==1时才会有值
  ///
  /// `country`: 国家，android上只有通过[AMapLocationOption.needAddress]为true时才有可能返回值
  ///
  /// `province`: 省，android上只有通过[AMapLocationOption.needAddress]为true时才有可能返回值
  ///
  /// `city`: 城市，android上只有通过[AMapLocationOption.needAddress]为true时才有可能返回值
  ///
  /// `district`: 城镇（区），android上只有通过[AMapLocationOption.needAddress]为true时才有可能返回值
  ///
  /// `street`: 街道，android上只有通过[AMapLocationOption.needAddress]为true时才有可能返回值
  ///
  /// `streetNumber`: 门牌号，android上只有通过[AMapLocationOption.needAddress]为true时才有可能返回值
  ///
  /// `cityCode`: 城市编码，android上只有通过[AMapLocationOption.needAddress]为true时才有可能返回值
  ///
  /// `adCode`: 区域编码， android上只有通过[AMapLocationOption.needAddress]为true时才有可能返回值
  ///
  /// `address`: 地址信息， android上只有通过[AMapLocationOption.needAddress]为true时才有可能返回值
  ///
  /// `description`: 位置语义， android上只有通过[AMapLocationOption.needAddress]为true时才有可能返回值
  ///
  /// `errorCode`: 错误码，当定位失败时才会返回对应的错误码， 具体错误请参考：https://lbs.amap.com/api/android-location-sdk/guide/utilities/errorcode
  ///
  /// `errorInfo`: 错误信息， 当定位失败时才会返回

   */
  void getLoc(LocationCall onCall)async{
    bool hasLocationPermission = await _requestLocationPermission();
    if (!hasLocationPermission) {//无权限
      return;
    }
    StreamSubscription<Map<String, Object>> _locationListener;
    AMapFlutterLocation _locationPlugin = new AMapFlutterLocation();
    AMapFlutterLocation.setApiKey(ConstKey.aMapAndroidKey, ConstKey.aMapIosKey);
    ///iOS 获取native精度类型
    if (Platform.isIOS) {
      AMapAccuracyAuthorization currentAccuracyAuthorization =
          await _locationPlugin.getSystemAccuracyAuthorization();
      if (currentAccuracyAuthorization ==
          AMapAccuracyAuthorization.AMapAccuracyAuthorizationFullAccuracy) {
        print("精确定位类型");
      } else if (currentAccuracyAuthorization ==
          AMapAccuracyAuthorization.AMapAccuracyAuthorizationReducedAccuracy) {
        print("模糊定位类型");
      } else {
        print("未知定位类型");
      }
    }

    ///注册定位结果监听
    _locationListener = _locationPlugin
        .onLocationChanged()
        .listen((Map<String, Object> result) {
          ///移除定位监听
          if (null != _locationListener) {
            _locationListener.cancel();
          }

          ///销毁定位
          if (null != _locationPlugin) {
            _locationPlugin.destroy();
          }

          onCall.call(result);
    });

    ///开始定位之前设置定位参数
    AMapLocationOption locationOption = new AMapLocationOption();

    ///是否单次定位
    locationOption.onceLocation = true;

    ///是否需要返回逆地理信息
    locationOption.needAddress = true;

    ///逆地理信息的语言类型
    locationOption.geoLanguage = GeoLanguage.DEFAULT;

    locationOption.desiredLocationAccuracyAuthorizationMode =
        AMapLocationAccuracyAuthorizationMode.ReduceAccuracy;

    locationOption.fullAccuracyPurposeKey = "AMapLocationScene";

    ///设置Android端连续定位的定位间隔
    locationOption.locationInterval = 2000;

    ///设置Android端的定位模式<br>
    ///可选值：<br>
    ///<li>[AMapLocationMode.Battery_Saving]</li>
    ///<li>[AMapLocationMode.Device_Sensors]</li>
    ///<li>[AMapLocationMode.Hight_Accuracy]</li>
    locationOption.locationMode = AMapLocationMode.Hight_Accuracy;

    ///设置iOS端的定位最小更新距离<br>
    locationOption.distanceFilter = -1;

    ///设置iOS端期望的定位精度
    /// 可选值：<br>
    /// <li>[DesiredAccuracy.Best] 最高精度</li>
    /// <li>[DesiredAccuracy.BestForNavigation] 适用于导航场景的高精度 </li>
    /// <li>[DesiredAccuracy.NearestTenMeters] 10米 </li>
    /// <li>[DesiredAccuracy.Kilometer] 1000米</li>
    /// <li>[DesiredAccuracy.ThreeKilometers] 3000米</li>
    locationOption.desiredAccuracy = DesiredAccuracy.Best;

    ///设置iOS端是否允许系统暂停定位
    locationOption.pausesLocationUpdatesAutomatically = false;

    ///将定位参数设置给定位插件
    _locationPlugin.setLocationOption(locationOption);

    ///开始定位
    _locationPlugin.startLocation();
  }

  /// 申请定位权限
  /// 授予定位权限返回true， 否则返回false
  Future<bool> _requestLocationPermission() async {
    //获取当前的权限
    var status = await Permission.location.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.location.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

}